package com.lagou.minicat.core;

import com.lagou.minicat.servlet.HttpRequest;

import javax.servlet.Servlet;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class Mapper {

    private Map<String, Host> hostMap = new HashMap<>();

    /**
     * Servlet匹配
     *
     * 例如: http://localhost:8080/demo01/lagou
     * 按规则截取出以下字段：
     * host             - localhost
     * contextPath      - /demo01
     * servletPath      - /lagou
     *
     * 然后通过wrapper集合去查找，目前只支持【精确】匹配
     *
     * @param httpRequest
     * @return
     */
    public Servlet matchServlet(HttpRequest httpRequest) throws Exception {
        // 查找Host
        Host host = hostMap.get(httpRequest.getHost());
        if (host != null) {
            // 查找Context
            Optional<Context> context = host.getContexts().stream()
                    .filter(c -> c.getPath().equals(httpRequest.getContextPath()))
                    .findFirst();

            if (context.isPresent()) {
                // 查找Wrapper
                Optional<Wrapper> wrapper = context.get().getWrappers().stream()
                        .filter(w -> w.getUrlPattern().equals(httpRequest.getServletPath()))
                        .findFirst();

                // 反射实例化Servlet对象
                if (wrapper.isPresent()) {
                    return wrapper.get().getServlet();
                }
            }
        }
        return null;
    }

    public void registerHost(Host host) {
        hostMap.put(host.getName(), host);
    }

}
